/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.WebIDE.ejb.sessions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.sessions.exceptions.*;

/**
 *
 * @author huy
 */
@Stateless
public class ProjectsFacade implements ProjectsFacadeLocal, ProjectsFacadeRemote {

    @Resource
    private UserTransaction utx = null;
    @PersistenceContext(unitName = "WebIDE-ejbPU")
    private EntityManager _em = null;
    /*    public void create(Projects projects) {
    em.persist(projects);
    }

    public void edit(Projects projects) {
    em.merge(projects);
    }
     */

    public void remove(Projects projects) {
        _em.remove(_em.merge(projects));
    }

    public Projects find(Object id) {
        return _em.find(Projects.class, id);
    }

    public List<Projects> findAll() {
        return _em.createQuery("select object(o) from Projects as o").getResultList();
    }

    public EntityManager getEntityManager() {
        return _em;
    }

    public void create(Projects projects) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (projects.getFilesCollection() == null) {
            projects.setFilesCollection(new ArrayList<Files>());
        }
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Languages language = projects.getLanguage();
            if (language != null) {
                language = em.getReference(language.getClass(), language.getId());
                projects.setLanguage(language);
            }
            Users userName = projects.getUserName();
            if (userName != null) {
                userName = em.getReference(userName.getClass(), userName.getUserName());
                projects.setUserName(userName);
            }
            Collection<Files> attachedFilesCollection = new ArrayList<Files>();
            for (Files filesCollectionFilesToAttach : projects.getFilesCollection()) {
                filesCollectionFilesToAttach = em.getReference(filesCollectionFilesToAttach.getClass(), filesCollectionFilesToAttach.getId());
                attachedFilesCollection.add(filesCollectionFilesToAttach);
            }
            projects.setFilesCollection(attachedFilesCollection);
            em.persist(projects);
            if (language != null) {
                language.getProjectsCollection().add(projects);
                language = em.merge(language);
            }
            if (userName != null) {
                userName.getProjectsCollection().add(projects);
                userName = em.merge(userName);
            }
            for (Files filesCollectionFiles : projects.getFilesCollection()) {
                Projects oldProjectIdOfFilesCollectionFiles = filesCollectionFiles.getProjectId();
                filesCollectionFiles.setProjectId(projects);
                filesCollectionFiles = em.merge(filesCollectionFiles);
                if (oldProjectIdOfFilesCollectionFiles != null) {
                    oldProjectIdOfFilesCollectionFiles.getFilesCollection().remove(filesCollectionFiles);
                    oldProjectIdOfFilesCollectionFiles = em.merge(oldProjectIdOfFilesCollectionFiles);
                }
            }
            //utx.commit();
            File f = new File(userName.getUserName()+"/"+ projects.getName());
            f.mkdirs();

        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findProjects(projects.getId()) != null) {
                throw new PreexistingEntityException("Projects " + projects + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void edit(Projects projects) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Projects persistentProjects = em.find(Projects.class, projects.getId());
            Languages languageOld = persistentProjects.getLanguage();
            Languages languageNew = projects.getLanguage();
            Users userNameOld = persistentProjects.getUserName();
            Users userNameNew = projects.getUserName();
            Collection<Files> filesCollectionOld = persistentProjects.getFilesCollection();
            Collection<Files> filesCollectionNew = projects.getFilesCollection();
            if (languageNew != null) {
                languageNew = em.getReference(languageNew.getClass(), languageNew.getId());
                projects.setLanguage(languageNew);
            }
            if (userNameNew != null) {
                userNameNew = em.getReference(userNameNew.getClass(), userNameNew.getUserName());
                projects.setUserName(userNameNew);
            }
            Collection<Files> attachedFilesCollectionNew = new ArrayList<Files>();
            for (Files filesCollectionNewFilesToAttach : filesCollectionNew) {
                filesCollectionNewFilesToAttach = em.getReference(filesCollectionNewFilesToAttach.getClass(), filesCollectionNewFilesToAttach.getId());
                attachedFilesCollectionNew.add(filesCollectionNewFilesToAttach);
            }
            filesCollectionNew = attachedFilesCollectionNew;
            projects.setFilesCollection(filesCollectionNew);
            projects = em.merge(projects);
            if (languageOld != null && !languageOld.equals(languageNew)) {
                languageOld.getProjectsCollection().remove(projects);
                languageOld = em.merge(languageOld);
            }
            if (languageNew != null && !languageNew.equals(languageOld)) {
                languageNew.getProjectsCollection().add(projects);
                languageNew = em.merge(languageNew);
            }
            if (userNameOld != null && !userNameOld.equals(userNameNew)) {
                userNameOld.getProjectsCollection().remove(projects);
                userNameOld = em.merge(userNameOld);
            }
            if (userNameNew != null && !userNameNew.equals(userNameOld)) {
                userNameNew.getProjectsCollection().add(projects);
                userNameNew = em.merge(userNameNew);
            }
            for (Files filesCollectionOldFiles : filesCollectionOld) {
                if (!filesCollectionNew.contains(filesCollectionOldFiles)) {
                    filesCollectionOldFiles.setProjectId(null);
                    filesCollectionOldFiles = em.merge(filesCollectionOldFiles);
                }
            }
            for (Files filesCollectionNewFiles : filesCollectionNew) {
                if (!filesCollectionOld.contains(filesCollectionNewFiles)) {
                    Projects oldProjectIdOfFilesCollectionNewFiles = filesCollectionNewFiles.getProjectId();
                    filesCollectionNewFiles.setProjectId(projects);
                    filesCollectionNewFiles = em.merge(filesCollectionNewFiles);
                    if (oldProjectIdOfFilesCollectionNewFiles != null && !oldProjectIdOfFilesCollectionNewFiles.equals(projects)) {
                        oldProjectIdOfFilesCollectionNewFiles.getFilesCollection().remove(filesCollectionNewFiles);
                        oldProjectIdOfFilesCollectionNewFiles = em.merge(oldProjectIdOfFilesCollectionNewFiles);
                    }
                }
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = projects.getId();
                if (findProjects(id) == null) {
                    throw new NonexistentEntityException("The projects with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Projects projects;
            try {
                projects = em.getReference(Projects.class, id);
                projects.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The projects with id " + id + " no longer exists.", enfe);
            }
            Languages language = projects.getLanguage();
            if (language != null) {
                language.getProjectsCollection().remove(projects);
                language = em.merge(language);
            }
            Users userName = projects.getUserName();
            if (userName != null) {
                userName.getProjectsCollection().remove(projects);
                userName = em.merge(userName);
            }
            Collection<Files> filesCollection = projects.getFilesCollection();
            for (Files filesCollectionFiles : filesCollection) {
                filesCollectionFiles.setProjectId(null);
                filesCollectionFiles = em.merge(filesCollectionFiles);
            }
            em.remove(projects);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public List<Projects> findProjectsEntities() {
        return findProjectsEntities(true, -1, -1);
    }

    public List<Projects> findProjectsEntities(int maxResults, int firstResult) {
        return findProjectsEntities(false, maxResults, firstResult);
    }

    private List<Projects> findProjectsEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Projects as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            //em.close();
        }
    }

    public Projects findProjects(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Projects.class, id);
        } finally {
            //em.close();
        }
    }

    public int getProjectsCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Projects as o").getSingleResult()).intValue();
        } finally {
            //em.close();
        }
    }
}
